#coding:utf-8
__author__ = 'Xiaodong.Yang'

"""
CopyRight(c)  FraPlus.Corp 2017
Date : 2017-06-15
"""

import base64
import tornado.ioloop
import tornado.web
from tornado.web import RequestHandler
from fralog.FraLog import  Fralog
import threading
import os,time
from fraMail.framail import FraMail
from utils.utils import IP,get_html_url,get_down_pdf_usr,send_email,nonblock_send_mail
from queue import Queue

from handler.FraHandler import FraHandler

log = Fralog().getFileLog()
mail_list = Queue()

class MailFifo(object):
    def __init__(self,email,order_no=None,total_amount='0.1', title = 'Fra+', msg = '' ):
        self.email = email
        self.order_no = order_no
        self.total_amount = total_amount
        self.title = title
        self.msg = msg

class KOL(object):
    def __init__(self):
        super(KOL).__init__()
        self.main = ''
        self.target = []
    def addTarget(self,account):
        self.target.append(account)
    def getMain(self):
        return self.main
    def getTarget(self):
        return self.target

class MailHandler(FraHandler):

    def options(self, *args, **kwargs):
        pass
    def get(self, *args):
        log.info('收到邮件推送请求，准备添加到任务队列')

        email = self.get_argument('email')
        order_no = self.get_argument('order_no')
        total_amount = self.get_argument('total_amount')

        title = self.get_argument('title').encode('gbk')
        msg = self.get_argument('msg')
        msg = msg.replace(' ', '+').encode('gbk')
        print(msg)
        title = base64.b64decode(title).decode('gbk')
        msg=base64.b64decode(msg).decode('gbk')

        mail_list.put(MailFifo(email,order_no,total_amount, title, msg))
        log.info('邮件推送任务（收件人{0}）,已添加到任务队列'.format(email))
        log.info('当前任务总数:{0}'.format(mail_list.qsize()))
        self.set_status(200,'OK')
        self.write('OK')

def make_app():
    settings = {
        "static_path": os.path.join(os.path.dirname(__file__), "static"),
        "xsrf_cookies": False,
    }

    return tornado.web.Application(
         handlers=  [
        (r"/mail", MailHandler)
    ],**settings)


def mail_loop():
     log.info('开启邮件服务......')
     fm = FraMail()
     fm.login()
     while True:
         if mail_list.empty():
             time.sleep(1)
         else:
             item = mail_list.get()
             email = item.email
             order_no = item.order_no
             total_amount = item.total_amount
             title = item.title
             msg = item.msg
             log.info('发送邮件, To:%s'%(email))
             mail_list.task_done()
             log.info('当前队列长度{0}'.format(mail_list.qsize()))
             #send_email(email,order_no,total_amount)
             #threading.Thread(target=send_email,args=(email,order_no,total_amount))
             nonblock_send_mail(fm, email, order_no, total_amount, title, msg)
             log.info('邮件已发送成功')



def mainfunc():
    app = make_app()
    app.listen(8899)
    threading.Thread(target=mail_loop).start()
    log.info('开启web API服务')
    tornado.ioloop.IOLoop.current().start()

if __name__ == '__main__':
    log.info('启动邮件服务.......')
    mainfunc()
